﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Helper;

/// <summary>
/// *========================
///  IO操作助手类
///  V1.1.100429 (CMS7)
///  by eXplorer
/// *========================
/// </summary>
namespace CMS.Helper
{
    public sealed class IOHelper
    {
        public IOHelper()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 获取服务器操作系统版本
        /// </summary>
        /// <returns>服务器操作系统版本</returns>
        public static string GetServerOS()
        {
            try
            {
                return Environment.OSVersion.ToString();
            }
            catch (Exception ex)
            {
                return "获取服务器操作系统版本失败;" + ex.Message;
            }
        }

        /// <summary>
        /// 获取服务器系统语言
        /// </summary>
        /// <returns>获取服务器系统语言</returns>
        public static string GetServerLanguage()
        {
            return CultureInfo.InstalledUICulture.EnglishName;
        }

        /// <summary>
        /// 获取服务器可用内存 !部分机器报错
        /// </summary>
        /// <returns>可用内存</returns>
        public static string GetServerRAM()
        {
            try
            {
                PerformanceCounter myMemory = new PerformanceCounter();
                myMemory.CategoryName = "Memory";
                myMemory.CounterName = "Available MBytes";
                return myMemory.NextValue().ToString() + "MB 可用";
            }
            catch (Exception ex)
            {
                return "程序错误,可能是没有权限;" + ex.Message;
            }
        }

        /// <summary>
        /// 获取服务器驱动器信息
        /// </summary>
        /// <returns>服务器驱动器信息</returns>
        public static string GetServerDrivers()
        {
            string[] achDrivers = Directory.GetLogicalDrives();
            string strReturn = "";
            for (int i = 0; i <= Directory.GetLogicalDrives().Length - 1; i += 1)
            {
                strReturn = strReturn + achDrivers[i].ToString() + " ";
            }
            return strReturn;
        }

        /// <summary>
        /// 获取服务器CPU个数
        /// </summary>
        /// <returns>服务器CPU个数</returns>
        public static string GetCPUNumber()
        {
            try
            {
                return Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");
            }
            catch (Exception ex)
            {
                return "获取服务器CPU个数失败;" + ex.Message;
            }
        }

        /// <summary>
        /// 获取服务器CPU类型
        /// </summary>
        /// <returns>服务器CPU类型</returns>
        public static string GetCPUType()
        {
            try
            {
                return Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");
            }
            catch (Exception ex)
            {
                return "获取服务器CPU类型失败;" + ex.Message;
            }
        }

        /// <summary>
        /// 获取.NET Framework版本
        /// </summary>
        /// <returns>.NET Framework版本</returns>
        public static string GetDotNetVersion()
        {
            try
            {
                return Environment.Version.ToString();
            }
            catch (Exception ex)
            {
                return "获取.NET版本号失败;" + ex.Message;
            }
        }

        /// <summary>
        /// 获取服务器时区
        /// </summary>
        /// <returns>服务器时区</returns>
        public static string GetTimeZone()
        {
            return ((DateTime.Now - DateTime.UtcNow).TotalHours > 0 ? "+" + (DateTime.Now - DateTime.UtcNow).TotalHours.ToString() : (DateTime.Now - DateTime.UtcNow).TotalHours.ToString());
        }

        /// <summary>
        /// 读取文本文件内容
        /// </summary>
        /// <param name="FilePath">文本文件路径[绝对]</param>
        /// <returns>文本文件内容</returns>
        public static string ReadTxtFile(string FilePath)
        {
            try
            {
                string FileExtName = null;
                string ReadFile = null;
                FileExtName = FilePath.Substring(FilePath.LastIndexOf(".") + 1, 3);
                if ((FileExtName != "txt" & FileExtName != "TXT"))
                {
                    return "文件类型错误!";
                }
                else
                {
                    System.IO.StreamReader FileStream = default(System.IO.StreamReader);
                    FileStream = new System.IO.StreamReader(FilePath, System.Text.Encoding.Default);
                    ReadFile = FileStream.ReadToEnd();
                    return ReadFile;
                }
            }
            catch (Exception ex)
            {
                return "系统错误;" + ex.Message;
            }
        }

        /// <summary>
        /// 保存为TXT
        /// </summary>
        /// <param name="Content">内容</param>
        /// <param name="SavePath">保存路径[绝对]</param>
        /// <param name="SaveFileName">文件名[无需写.txt]</param>
        /// <returns>是否成功</returns>
        public static bool SaveAsTxt(string Content, string SavePath, string SaveFileName)
        {
            if (CommonFunctions.Right(SaveFileName, 4).ToLower() == ".txt")
            {
                SaveFileName = SaveFileName.Replace(".txt", "");
            }
            try
            {
                FileStream fs = new FileStream(SavePath + SaveFileName + ".txt", FileMode.Open, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("utf-8"));
                sw.Flush();
                sw.BaseStream.Seek(0, SeekOrigin.End);
                sw.WriteLine(Content);
                sw.Flush();
                sw.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="upFile">上传控件的ID</param>
        /// <param name="SavePath">保存路径</param>
        /// <returns>是否成功</returns>
        public static bool UploadFile(FileUpload upFile, string SavePath)
        {
            try
            {
                upFile.PostedFile.SaveAs(SavePath);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="delFilePath">文件路径[绝对]</param>
        /// <returns>是否成功</returns>
        public static bool DeleteFile(string delFilePath)
        {
            try
            {
                FileInfo fi = new FileInfo(delFilePath);
                fi.Delete();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 建立文件夹
        /// </summary>
        /// <param name="path">文件夹路径[绝对]</param>
        /// <returns>是否成功</returns>
        public static bool CreatFolder(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">文件夹路径[绝对]</param>
        /// <returns>是否成功</returns>
        public static bool DeleteFolder(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    foreach (string d in Directory.GetFileSystemEntries(path))
                    {
                        if (File.Exists(d))
                        {
                            File.Delete(d);
                        }
                        else
                        {
                            DeleteFolder(d);
                        }
                    }
                    Directory.Delete(path, true);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="dirpath">文件夹路径[绝对]</param>
        /// <returns>大小</returns>
        public static long GetDirectorySize(string dirpath)
        {
            try
            {
                if (!Directory.Exists(dirpath))
                {
                    return -1;
                }
                long len = 0;
                DirectoryInfo di = new DirectoryInfo(dirpath);
                foreach (FileInfo fi in di.GetFiles())
                {
                    len += fi.Length;
                }
                DirectoryInfo[] dis = di.GetDirectories();
                if (dis.Length > 0)
                {
                    for (int i = 0; i <= dis.Length - 1; i++)
                    {
                        len += GetDirectorySize(dis[i].FullName);
                    }
                }
                return len;
            }
            catch (Exception)
            {
                return -100;
            }
        }

        /// <summary>
        /// 大小单位
        /// </summary>
        public enum LenMeasure
        {
            B, KB, MB, GB
        }

        /// <summary>
        /// 获取文件大小并返回不同单位的结果
        /// </summary>
        /// <param name="FilePath">文件路径[绝对]</param>
        /// <param name="measure">大小单位</param>
        /// <returns>大小</returns>
        public static long GetFileLenByMeasure(string FilePath, LenMeasure measure)
        {
            try
            {
                if (!File.Exists(FilePath))
                {
                    return -1;
                }
                FileInfo f = new FileInfo(FilePath);
                long myfilelen = f.Length;
                if (measure == LenMeasure.B)
                {
                    return myfilelen;
                }
                else if (measure == LenMeasure.KB)
                {
                    return Convert.ToInt32(myfilelen / 1024);
                }
                else if (measure == LenMeasure.MB)
                {
                    return myfilelen / 1024 / 1024;
                }
                else if (measure == LenMeasure.GB)
                {
                    return myfilelen / 1024 / 1024;
                }
                else
                {
                    return -10;
                }
            }
            catch (Exception)
            {
                return -100;
            }
        }

        /// <summary>
        /// 获取文件修改日期
        /// </summary>
        /// <param name="filePath">文件路径[绝对]</param>
        /// <returns>修改日期</returns>
        public static DateTime GetFileDateTime(string filePath)
        {
            FileInfo f = new FileInfo(filePath);
            return f.LastWriteTime;
        }

        /// <summary>
        /// 执行CMD命令[慎用]
        /// </summary>
        /// <param name="strCmd">CMD命令</param>
        /// <returns>回显</returns>
        public string ExecCmd(string strCmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string strOutput = "";
            try
            {
                p.Start();
                p.StandardInput.WriteLine(strCmd);
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                p.Close();
            }
            catch (Exception ex)
            {
                strOutput = ex.Message;
            }
            return strOutput;
        }
    }
}